<?php
    @session_start();
require_once 'shared-functions.php';
require_once 'session.php';
require_once 'masterpage.php';

if (!IsValidSession()) {
    header('Location: login.php?page=process-payment');
    exit();
}
else
{
    RefreshSession();
}

$user = GetCurrentUserAccessLevel();

//Check user access
if ($user != $DIRECTOR && $user != $ADMIN && $user != $REGISTRAR) {
    header('Location: login.php?page=process-payment&error=To access to the process payment page, please log in as a director, admin or registrar&logout=1');
    exit();
}

if (!isset($_POST['StudentID'])) {
    header('Location: student-selector.php?page=process-payment');
    exit();
}


$link = connect_db();

masterpage("Process Payment");
//Used for error checking
$a = "";

$_SESSION['dateTime'] = $dateTime = date('Y-m-d H:i:s');
$_SESSION['studentID'] = $studentID = $_POST['StudentID'];
//Process Payment
if (isset($_POST['paymentMethod']) && isset($_POST['type']) && isset($_POST['amount']) && isset($_POST['comment'])) {
    $showMessage = false;
    $msg = "";
    $premsg = "<td class='altrows'>";

    $query = "SELECT * FROM `FeeLedger` WHERE `StudentID` = '" . $_POST['StudentID'] . "';";
    $result = mysql_query($query, $link);

    $total = 0;
    while ($ledgerEntry = mysql_fetch_array($result, MYSQL_BOTH))
    {
        $total += $ledgerEntry['Amount'];
    }


    if ($_POST['amount'] != "") {
        if (is_numeric($_POST['amount'])) {
            //Validated... now perform adding the payment

            $amount = $_POST['amount'];

            if (!isset($_POST['revert'])) {
                if ($amount > 0) {
                    $amount = -($amount);
                }
            }
            else //If reverting
            {
                if ($amount < 0) {
                    $amount = -($amount);
                }
                $_POST['comment'] = "Reverted last transaction";
            }

            $query = "INSERT INTO `FeeLedger` (`StudentID`,
                                  `Date`,
                                  `Type`,
                                  `Amount`,
                                  `Comment`,
                                  `ProcessingUser`,
                                  `PaymentMethod`) VALUES
                                  ('" . $_POST['StudentID'] . "',
                                   '" . $dateTime . "',
                                   '" . $_POST['type'] . "',
                                   '" . $amount . "',
                                   '" . $_POST['comment'] . "',
                                   '" . GetSessionUser() . "',
                                   '" . $_POST['paymentMethod'] . "');";
            $result = mysql_query($query, $link);
            if (!$result) {
                $showMessage = true;
                $msg = "Oops something went wrong. Please contact support.";

                addLogEntry('FeeLedger', 'Unsuccessfully added ' . $amount . ' GHC payment for Student: ' . $_POST['StudentID']);
            }
            else
            {
                $showMessage = true;
                if (!isset($_POST['revert'])) {
                    $msg = "Payment of " . -($amount) . " GH&cent; complete. [ <a href='print-receipt.php' target='_blank'>Print Receipt</a> ]<form action='process-payment.php' method='post'>
                                                                        <input type='hidden' name='StudentID' value='" . $_POST['StudentID'] . "' />
                                                                        <input type='hidden' name='paymentMethod' value='" . $_POST['paymentMethod'] . "' />
                                                                        <input type='hidden' name='type' value='" . $_POST['type'] . "' />
                                                                        <input type='hidden' name='amount' value='" . $_POST['amount'] . "' />
                                                                        <input type='hidden' name='comment' value='" . $_POST['comment'] . "' />
                                                                        <input type='hidden' name='revert' value='1' />
                                                                        <input type='submit' value='Revert' alt='Click here to revert the last payment' />
                                                                    </form>";
                    addLogEntry('FeeLedger', 'Added ' . $amount . ' GHC payment for Student: ' . $_POST['StudentID']);
                }
                else
                {
                    $msg = "Transaction reverted [ <a href='print-receipt.php' target='_blank'>Print Receipt</a> ]";
                    addLogEntry('FeeLedger', 'Reverted ' . $amount . ' GHC payment for Student: ' . $_POST['StudentID']);
                }
            }

        }
        else
        {
            $showMessage = true;
            $a = "<font color='red'>*</font>";
            $msg = $_POST['amount'] . " GH&cent; is not a valid amount. Please enter a corrent amount.";
        }
    }
    else
    {
        $showMessage = true;
        $a = "<font color='red'>*</font>";
        $msg = "Please enter an amount";
    }

    if ($showMessage) {
        echo '<table width="800"><tr class="altrows">' . $premsg . $msg . '</td></tr></table>';
    }
}
?>
<a href='student-selector.php?page=process-payment'>&lt;&lt; Back to Student Selector</a>
<br/>
<br/>
<table>
    <form action="process-payment.php" method="post">
		<input type="hidden" name="StudentID" value="<?php echo $studentID; ?>"/>
        <tr>
            <th class="tableTitle" colspan="2">Process Payment</th>
        </tr>
        <tr>
            <td class="fieldLabel">Student ID</td>
            <td><?php echo $studentID; ?></td>
        </tr>
<?php
		// Get Student Info to display
		$query = "SELECT `FirstName`, `MiddleName`, `LastName`, `DOB`
					FROM `Student` JOIN `User`
						ON Student.ID = User.UserId
					WHERE Student.ID = '$studentID';";
					
		$result = mysql_query($query,$link);
		$studentInfo = mysql_fetch_array($result,MYSQL_BOTH);
		
		echo "<tr><td class='fieldLabel'>Name</td>";
		echo "<td>".$studentInfo['FirstName']." ".$studentInfo['MiddleName']." ".$studentInfo['LastName']."</td></tr>";
		echo "<tr><td class='fieldLabel'>Birthday</td>";
		echo "<td>".date('d-m-Y', strtotime($studentInfo['DOB']))."</td></tr>";
?>
		<tr>
        <td class="fieldLabel">Payment Method</td>
        <td>
            <select name="paymentMethod">
                <option value="1">Cash</option>
                <option value="2">Account Transfer</option>
                <option value="3">Money Order/Bank Draft</option>
            </select>
        </td>
        </tr>
        <tr>
            <td class="fieldLabel">Payment Category</td>
            <td><select name="type">
<?php
        $query = "SELECT * FROM `feeTypes` WHERE `description` LIKE '%Payment';";
    $result = mysql_query($query, $link);
    while ($currentType = mysql_fetch_array($result, MYSQL_BOTH))
    {
        $selected = "";
        if($currentType['description'] == 'Payment')
        {
            $selected = " selected ";
        }
        echo '<option value="' . $currentType['type'] . '" '.$selected.'>' . $currentType['description'] . "</option>";
    }
    ?>
            </select></td>
        </tr>
        <tr>
            <td class="fieldLabel">Amount</td>
            <td><input type="text" name="amount"/><?php echo $a;?></td>
        </tr>
        <tr>
            <td class="fieldLabel">Comment</td>
            <td><textarea rows="5" cols="30" name="comment"></textarea></td>
        </tr>
        <tr>
            <td colspan="2" align="right"><input type="submit" value="Add Payment"/></td>
        </tr>
    </form>
</table>
<br/>

<form action="student-billing-history.php" method="POST" target="_blank">
	<input type="submit" value="View Printer Friendly History"/>
	<input type="hidden" name="StudentID" value="<?php echo $studentID;?>"/>
</form>
	
<table class="DataList">
    <tr>
        <th class="header" colspan="5">Payment History</th>
    </tr>
    <tr>
        <th class="header">Date</th>
        <th class="header">Transaction Type</th>
        <th class="header">Amount</th>
        <th class="header">User</th>
        <th class="header">Notes</th>
    </tr>
<?php
        $query = "SELECT `FeeLedger`.`Date`, 
                         `FeeLedger`.`Amount`,
                         `FeeLedger`.`ProcessingUser`,
                         `FeeLedger`.`Comment`,
                         `feeTypes`.`description`
                         FROM `FeeLedger`,`feeTypes` WHERE `StudentID`='" . $_POST['StudentID'] . "' AND `FeeLedger`.`Type`=`feeTypes`.`type` ORDER BY `Date` ASC;";
    $result = mysql_query($query, $link);
    $accountBalance = 0;
    $rowID = 0;
    while ($ledgerEntry = mysql_fetch_array($result, MYSQL_BOTH))
    {

        if ($rowID == 0) {
            $rowClass = "rows";
            $rowID++;
        }
        else
        {
            $rowClass = "altrows";
            $rowID--;
        }

        $accountBalance += $ledgerEntry['Amount'];
        echo '<tr class="' . $rowClass . '">';
        echo '<td>' . date('d-m-Y H:i:s', strtotime($ledgerEntry['Date'])) . "</td>";
        echo '<td>' . $ledgerEntry['description'] . "</td>";
        echo '<td>' . $ledgerEntry['Amount'] . "</td>";
        echo '<td>' . $ledgerEntry['ProcessingUser'] . "</td>";
        echo '<td>' . $ledgerEntry['Comment'] . "</td>";
        echo '</tr>';
    }
    echo '<tr><td></td><td>Current Balance</td><td>' . number_format($accountBalance, 2) . ' GH¢</td><td></td><td></td></tr>';
    ?>
</table>

<?php
	echo "<br/>";
	echo "<form action='apply-fee.php' method='POST'>";
	echo "<input type='submit' value='Go to Apply Fee Page'/>";
	echo "<input type='hidden' name='StudentID' value='$studentID'/>";
	echo "</form>";
	
    endmasterpage();
?>

